
 #include <unistd.h>
 #include <sys/types.h>
 #include<iostream>
 #include<vector>
 #include<functional>
 #include<string>
 #include<wait.h>
 #include"channel.hpp"
 #include"taskmanager.hpp"

using namespace std;

enum 
{
    OK,
    UsageError,
    PipeError,
    ProcessError

};
class processpool
{
public:
    int initprocesspool(int num,work_t work)
    {
        for(int i=0;i<num;i++)
        {
            
            int pipefd[2];
            int n=pipe(pipefd);
            if(n<0)
            {
                return PipeError;
            }

            pid_t id=fork();
            if(id<0)
            {
                return ProcessError;
            }

            if(id==0)
            {
                //std::cout<<getpid()<<std::endl;

                ::close(pipefd[1]);
                for(auto& c:channels)//确保每个管道只有一个写端
                {
                    ::close(c.getwfd());
                }
                dup2(pipefd[0],0);//这样在读取时就不用传fd了
                work();
                exit(0);

            }

            ::close(pipefd[0]);
            channels.emplace_back(pipefd[1],id);//写时拷贝，这样就不会影响子进程的channels




        }
        return OK;

    }

    void dispatchtask(int n)
    {
        int who=0;
        cout<<n<<endl;
        while(n--)
        {
            
            int task=tm.select();
            
            channel &cur=channels[who++];//选择哪个管道
            who %=channels.size();
            //cout<<"send task "<<task<<" to "<<cur.getid()<<endl;
            cur.send(task);
            //cout<<"send task "<<task<<" to "<<cur.getid()<<endl;

            sleep(1);
        }
    }


    void cleanprocesspool()
    {
        for(auto& c:channels)
        {
            ::close(c.getwfd());
            int id= waitpid(c.getid(),nullptr,0);
            if(id>0)
            {
                cout<<"wait "<<id<<" success"<<endl;
            }

        }

    }
private:
    vector<channel> channels;


};